//
//  EFAPjtDevSeaICCIDVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/10/25.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAPjtDevSeaICCIDVC.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "EFAModel.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "UIColor+XDHex.h"
#import "EFAUtyQRScanVC.h"

@interface EFAPjtDevSeaICCIDVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource, UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UIButton *scanBtn;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;
@property (strong, nonatomic) EFAPjtIotModel *iotModel;
@end

static NSString *const kReuseCellId = @"UITableViewCell";
static NSInteger const kRequestSize = 20;

@implementation EFAPjtDevSeaICCIDVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}
- (void)initNavigationBar {
    // 设置导航控制器的代理为self
    self.navigationController.delegate = self;
}
- (void)initSubViews {
    self.textField.layer.masksToBounds = YES;
    self.textField.layer.cornerRadius = 4.0f;
    [self.textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    [self.cancelBtn addTarget:self action:@selector(cancelBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.scanBtn addTarget:self action:@selector(scanBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
    self.tableView.mj_footer = self.mj_footer;
    
    [self.tableView.mj_header beginRefreshing];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"没有检索到相关ICCID" attributes:dic];
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    //    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
    return nil;
}
//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}
#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isSelf = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isSelf animated:YES];
}
#pragma mark - UITableViewDataSource
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return 1;
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.iotModel.efairyiotcard_list.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    cell.textLabel.font = [UIFont systemFontOfSize:14.0];
    EFAPjtIotItem *item = self.iotModel.efairyiotcard_list[indexPath.row];
    cell.textLabel.textColor = item.efairyiotcard_is_used ? [UIColor xd_colorWithHex:EFAGlobalColorFontLightBlack]: [UIColor xd_colorWithHex:EFAGlobalColorFontMidBlack];
    NSString *str = item.efairyiotcard_number;
    if (item.efairyiotcard_is_used) {
        str = [NSString stringWithFormat:@"%@[已使用]", item.efairyiotcard_number];
    }
    cell.textLabel.text = str;
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 14.9;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row < self.iotModel.efairyiotcard_list.count) {
        EFAPjtIotItem *item = self.iotModel.efairyiotcard_list[indexPath.row];
        [self backToParentWithICCID:item.efairyiotcard_number];
    }
}
#pragma mark - event response
- (void)textFieldDidChange:(UITextField *)textField {
    NSLog(@"搜索输入的内容:%@", textField.text);
    if (textField.text != nil) {
        [self requestPjtIotListWithHeader:YES];
    }
    
    //!< 扫一扫的状态显示
    self.scanBtn.hidden = textField.text.length;
}
- (void)scanBtnTapped:(UIButton *)btn {
    EFAUtyQRScanVC *vc = [[EFAUtyQRScanVC alloc] init];
    vc.successHandle = ^(NSString *qrCodeStr) {
        if (!qrCodeStr || ![qrCodeStr hasPrefix:@"8986"]) {
            NSString *msg = [NSString stringWithFormat:@"无效条码：%@", qrCodeStr];
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
            return ;
        }
        // 不够20位，补0
        if (qrCodeStr.length != 20) {
            NSInteger cnt = 20 - (NSInteger)qrCodeStr.length;
            for (NSInteger i = 0; i < cnt; i++) {
                qrCodeStr = [qrCodeStr stringByAppendingString:@"0"];
            }
        }
        self.textField.text = qrCodeStr;
        self.scanBtn.hidden = YES;
        [self requestPjtIotListWithHeader:YES];
    };
    [self showViewController:vc sender:nil];
}
- (void)cancelBtnTapped:(UIButton *)btn {
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - private methods
- (void)backToParentWithICCID:(NSString *)iccid {
    [self dismissViewControllerAnimated:YES completion:^{
        if (self.successHandle) {
            self.successHandle(iccid);
            self.successHandle = nil;
        }
    }];
}
- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.iotModel.totalLoad) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
    }
    self.tableView.mj_footer.hidden = self.iotModel.totalZero;
    
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestPjtIotListWithHeader:isHeader];
}

- (EFAPjtIotModel *)deviceModelWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[EFAGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.iotModel;
    }
    
    EFAPjtIotModel *temp = [EFAPjtIotModel yy_modelWithDictionary:dic[EFAGlobalJsonKeyResult]];
    if (!temp) {
        return self.iotModel;
    }
    
    if (AddMore && self.iotModel) {
        [self.iotModel addMoreWithData:temp];
    } else {
        self.iotModel = temp;
    }
    return self.iotModel;
}
#pragma mark - network request
- (void)requestPjtIotListWithHeader:(BOOL)isHeader {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        [self tableViewEndRefresh:isHeader];
        return;
    }
    
    NSInteger last_id = isHeader ? 0 : self.iotModel.efairyiotcard_list.lastObject.efairyiotcard_id;
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) forKey:@"efairyuser_id"];
    [pars setObject:[EFAModel sharedInstance].loginInfo.access_token forKey:@"access_token"];
    [pars setObject:(self.textField.text ? self.textField.text : @"") forKey:@"efairyiotcard_number"];
    [pars setObject:@(last_id) forKey:@"last_id"];
    [pars setObject:@(kRequestSize) forKey:@"size"];
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiPjtIotCardList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求iot列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        [self deviceModelWithDictionary:responseObject isAddMore:!isHeader];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求iot列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
//        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

@end
